package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbutil.DBUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * Servlet implementation class GetMessagesServlet
 */
@WebServlet("/GetMessagesServlet")
public class GetMessagesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMessagesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unused")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		JSONArray jsonarray = new JSONArray();
		response.setContentType("text/html;charset=utf-8");
  		request.setCharacterEncoding("UTF-8");
  		
  		String sql = request.getParameter("sql");
  		DBUtil db=new DBUtil();
		Connection conn = db.getConn();
		try {
//			String sql = "select * from newsdetail";
			ResultSet rs = db.getResult(sql);
			
			while(rs.next()) {
				JSONObject jsonobj = new JSONObject();
				jsonobj.put("Mid",rs.getInt("Mid"));
  				jsonobj.put("title",rs.getString("title"));
  				jsonobj.put("content",rs.getString("content"));
  				jsonobj.put("author",rs.getString("author"));
  				jsonobj.put("time",rs.getString("time"));
  				jsonobj.put("type",rs.getString("type"));
  				jsonobj.put("tname",rs.getString("tname"));
  				jsonarray.put(jsonobj);
			}
			response.getWriter().println(jsonarray);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(db!=null)
				db.release();//关闭数据库
		} 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
